<?php
$students = $_GET['students'];
$cows = $_GET['column'];
$order = $_GET['order'];

$allStudents = preg_split('/\r\n/', $students, -1, PREG_SPLIT_NO_EMPTY);
$studentsArray = [];

$id = 1;
foreach ($allStudents as $stud) {
    $studentsArray[] = $id . ', ' . $stud;
    $id++;
}

$tempStudent = [];

foreach ($studentsArray as $student) {
    $tempStudent[] = preg_split('/, /', $student, -1, PREG_SPLIT_NO_EMPTY);
}

$types = ['Id', 'Username', 'Email', 'Type', 'Result'];
$finalStudent = [];

for ($i = 0; $i < count($tempStudent); $i++) {
    for ($j = 0; $j < count($types); $j++) {
        $finalStudent[$i][$types[$j]] = $tempStudent[$i][$j];
    }
}

if ($order == 'descending') {

    if ($cows == 'result') {
        usort($finalStudent, function($a, $b) {
            return $b['Result'] - $a['Result'];
        });
    } elseif ($cows == 'username') {
        usort($finalStudent, function($a, $b) {
            return $b['Username'] > $a['Username'];
        });
    } elseif ($cows == 'id') {
        krsort($finalStudent);
    }

} else {

    if ($cows == 'result') {
        usort($finalStudent, function($a, $b) {
            return $a['Result'] - $b['Result'];
        });
    } elseif ($cows == 'username') {
        usort($finalStudent, function($a, $b) {
            return $a['Username'] > $b['Username'];
        });
    } elseif ($cows == 'id') {
        ksort($finalStudent);
    }

}

echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Id</th>";
echo "<th>Username</th>";
echo "<th>Email</th>";
echo "<th>Type</th>";
echo "<th>Result</th>";
echo "</tr>";
echo "</thead>";

foreach ($finalStudent as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>";
}

echo "</table>";
?>